//
// Created by wrp on 2023/6/7.
//
#include "local_beaver.h"
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <netinet/in.h>


#define WORKER_THread 4

typedef struct {
    int efd;
    int k;
}ARGS;

int createSocket() {
    int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (fd < 0) {
        printf("create socket error");
        return 0;
    }

    int r= setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,1);


    struct sockaddr_in sockAddr;
    sockAddr.sin_port = htons(8398);
    sockAddr.sin_family = AF_INET;
    sockAddr.sin_addr.s_addr = htons(INADDR_ANY);

    if (bind(fd, (struct sockaddr *) &sockAddr, sizeof(sockAddr)) < 0) {
        printf("bind socket error, port:8398");
        return 0;
    }

    if (listen(fd, 100) < 0) {
        printf("listen port error");
        return 0;
    }
    return fd;
}

void Worker(void *args) {
    ARGS tmp = *(ARGS *)args;
    int socketFd = tmp.efd;
    int k=tmp.k;
    printf("Worker %d runs\n",k);

    int efd = init(socketFd);
//    printf("worker %d init finish\n",k);

    struct epoll_event events[NATIVE_EVENT_MAX];

    while (1) {
        int eNum = epoll_wait(efd, events, NATIVE_EVENT_MAX, -1);
        if (eNum < 0) {
            printf("worker %d epoll error\n",k);
            return;
        }
//        else{
//            printf("worker %d epoll success\n",k);
//        }

//        sleep(1);
        printf("worker %d in\n",k);
        int i;
        for (i = 0; i < eNum; ++i) {
            if (events[i].data.fd == socketFd) {
                int tfd = 0;
                struct sockaddr_in cli_addr;
                socklen_t length = sizeof(cli_addr);
                tfd = accept(socketFd, (struct sockaddr *) &cli_addr, &length);
                if (tfd <= 0) {
                    printf("worker %d accept error\n",k);
                } else {
                    printf("worker %d accept\n",k);
                }
            }
        }
    }
}

int main() {
    int fd=createSocket();

    pthread_t th1;
    pthread_t th2;
    pthread_t th3;
    pthread_t th4;

    ARGS a1={fd,1};
    ARGS a2={fd,2};
    ARGS a3={fd,3};
    ARGS a4={fd,4};

    pthread_create(&th1,NULL,(void *)Worker,(void *)&a1);
    pthread_create(&th2,NULL,(void *)Worker,(void *)&a2);
    pthread_create(&th3,NULL,(void *)Worker,(void *)&a3);
    pthread_create(&th4,NULL,(void *)Worker,(void *)&a4);

    pthread_join(th1,NULL);
    pthread_join(th1,NULL);
    pthread_join(th1,NULL);
    pthread_join(th1,NULL);
}
